import { onBeforeRouteLeave } from 'vue-router';

import { ElMessageBox } from 'element-plus';
import { StatusControl } from '@/components/Table/hooks/useStatus';
import { TableRow } from '@/components/Table/ManageTable/model';

export const useLeaveTable = (
  statusControl: StatusControl<unknown>,
  handleSaveClose: (row: TableRow) => void
): void => {
  onBeforeRouteLeave((to, from, next) => {
    if (statusControl.status === 1 || statusControl.status === 2) {
      ElMessageBox.confirm('系统可能不会保存您所做的更改, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          handleSaveClose(statusControl.data as TableRow);
          next();
        })
        .catch(() => {
          next(false);
        });
    } else {
      next();
    }
  });
};
